package com.vimhe.easyimport.processor;

import com.vimhe.easyimport.config.bean.FileConfig;
import com.vimhe.easyimport.config.bean.SheetConfig;
import com.vimhe.easyimport.exception.ImportException;
import com.vimhe.easyimport.util.ValidateUtils;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

/**
 * 默认数据处理器
 * <p>通过指定一个数据源，自动按照每个工作表为一个批次把数据批量插入到指定的数据表中</p>
 *
 * @author Vimhe
 */
public final class DefaultDataProcessor extends AbstractDataProcessor {

    private final FileConfig fileConfig;
    private final DataSource dataSource;

    public DefaultDataProcessor(FileConfig fileConfig, DataSource dataSource) {
        this.fileConfig = fileConfig;
        this.dataSource = dataSource;
    }

    @Override
    public void processSheet(int sheetIndex, Map<Integer, Map<String, Object>> sheetValue) {
        try {
            SheetConfig sheetConfig = fileConfig.getSheetConfigs().get(sheetIndex);
            if (sheetConfig == null) {
                return;
            }
            if (ValidateUtils.isEmpty(sheetConfig.getTable())) {
                throw new ImportException("未配置表名称映射");
            }

            JdbcUtils jdbcUtils = new JdbcUtils(dataSource);
            Collection<Map<String, Object>> rowDataList = sheetValue.values();
            jdbcUtils.insertBatch(sheetConfig.getTable(), new ArrayList<>(rowDataList), sheetConfig.getRowConfig().getCellConfigs());
        } catch (Exception e) {
            throw new ImportException("导入数据出错：" + e.getMessage());
        }
    }

}
